package com.cts.tmall.app.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cts.tmall.biz.service.UserService;
import com.cts.tmall.com.exception.SystemException;
import com.cts.tmall.com.message.RspCode;
import com.cts.tmall.dal.entity.SysUser;
import com.google.common.collect.ImmutableMap;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Insert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.Map;

@RestController
@RequestMapping("/api/user")
public class UserController extends BaseController<SysUser> {
    @Autowired
    private UserService userService;

    @PostMapping
    public SysUser save(@RequestBody @Validated(Insert.class) SysUser entity) {
        entity.setSalt(RandomStringUtils.randomNumeric(10));
        entity.setPassword(DigestUtils.sha256Hex(entity.getPassword() + entity.getSalt()));
        entity.setStatus("00");
        userService.getMapper().insert(entity);
        return entity;
    }

    @PostMapping("/login")
    public Map<String, Object> login(@RequestBody SysUser user) throws Exception {
        user = userService.login(user.getLoginName(), user.getPassword());
        return ImmutableMap.of("token", user.getToken());
    }

    @PostMapping("/logout")
    public Map<String, Object> logout() throws Exception {
        return ImmutableMap.of("isLogout",true);
    }

    @GetMapping("/info")
    public Map<String, Object> info(@RequestHeader("Access-Token") String token) throws Exception {
        if (StringUtils.isBlank(token)) {
            throw new SystemException(RspCode.FAILURE_SYSTEM, "请先登录");
        }
        SysUser user = userService.getMapper().selectOne(Wrappers.<SysUser>lambdaQuery().eq(SysUser::getToken, token));
        String role = user.getRole();
        boolean isTeacher = StringUtils.isNotBlank(role) && "01".equals(role);

        return ImmutableMap.<String, Object>builder()
                .put("token", RandomStringUtils.randomNumeric(20))
                .put("id",user.getId())
                .put("name", user.getName())
                .put("avatar", user.getAvatar())
                .put("role", ImmutableMap.of("id", isTeacher ? "teacher" : "student", "name", isTeacher ? "老师" : "学生", "permissions", Arrays.asList(ImmutableMap.of("permissionId", isTeacher ? "teacher" : "student"))))
                .build();
    }
}
